/**
 * @(#)ThirdLoginAdapterHandler.java 2017年2月21日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.hziee.common.queue.DelayExecuteBuffer;
import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.*;
import org.jsbd.boss.domian.channel.*;
import org.jsbd.boss.enums.*;
import org.jsbd.boss.service.*;
import org.jsbd.boss.timer.TaskAdapterHandler;
import org.jsbd.boss.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.*;

/**
 * 第三方用户服务
 *
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
public abstract class ThirdLoginAdapterHandler<T extends ThirdUser> extends TaskAdapterHandler {
    public static final Logger LOGGER = LoggerFactory.getLogger(ThirdLoginAdapterHandler.class);


    @Resource
    protected RedisClient<String, Object> redisClientTemp;
    @Resource
    private IChannelApkConfigDAO channelApkConfigDAO;

    @Resource(name = "newTaskService")
    private INewTaskService newTaskService;

    @Resource
    private IApkLoginTypeService apkLoginTypeService;

    @Resource
    private SimulatorManager simulatorManager;
    @Resource
    private TaskLuaManager taskLuaManager;

    protected String loginIndexKey;
    protected LoginTypeEnum loginType;
    protected String queueKey;

    @Resource
    protected ApkManager apkManager;

    private final static String URL = PropertiesUtil.getValue("self_card_reuse_url");
    @Resource
    protected ClientManager clientManager;

    @Resource
    private CacheParamManager cacheParamManager;

    @Resource
    private IChannelApkInfoService channelApkInfoService;


    @Resource
    private ISimulatorLogService simulatorLogService;

    @Resource
    private IProvinceService provinceService;

    @Resource
    private IUserClientInfoService userClientService;

    protected int SELF_MAO_USER_MAX_TIME = 60000;


    @Resource(name = "allMiguUserDAO")
    private IMiguUserDAO allMiguUserDAO;


    @Resource(name = "miguEffectDelBuffer")
    private DelayExecuteBuffer<ClientEffectVo> miguEffectDelBuffer;

    @Resource(name = "miguRecordUpdateBuffer")
    private DelayExecuteBuffer<ClientRecordVo> miguRecordUpdateBuffer;

    @Resource
    private IMiguProvinceConfigDao miguProvinceConfigDao;
    @Resource
    private IClientEffectDAO clientEffectDAO;


    public abstract List<T> selectUserList(ThirdUserQueryVo queryVo);

    public boolean batchInsert(T user) {
        return false;
    }

    public List<MarkDayTask> selectRetentTaskList() {
        return null;
    }


    @Resource
    private IDeviceConfigDAO deviceConfigDAO;

    @Override
    public void run() {
        if (!init()) {
            return;
        }
        int expireTime = 10;
        Object refreshTime = cacheParamManager.getParamValue(CacheKey.T_L_REFRESH);
        if (refreshTime != null) {
            expireTime = Integer.parseInt(refreshTime.toString());
        }
        updateLoginUserToQueue(expireTime);
        updateLoginTask(expireTime);
    }

    private void updateLoginUserToQueue(int expireTime) {
        if (redisClient.evalSetNx(CacheKey.THIRD_USR_LOCK + loginType.getType() + "QUEUE", expireTime)) {
            //基地  运营商 就不过滤了 直接取三个运营商
            List<ApkLoginTypeConfig> loginTypeList = apkLoginTypeService.selectLoginBaseList(loginType.getType());
            int maxSize = 10;
            Object maxCacheLength = cacheParamManager.getParamValue(CacheKey.USER_CACHE_LENGTH);
            if (maxCacheLength != null) {
                maxSize = Integer.parseInt(maxCacheLength.toString());
            }
            CarrierEnum[] carrierEna = initQueryCarrier();
            for (ApkLoginTypeConfig config : loginTypeList) {
                for (CarrierEnum carrierEnum : carrierEna) {
                    for (int i = -1; i < 31; i++) {
                        Integer provinceId = i;
                        Integer base = config.getBase();
                        Integer apkId = config.getApkId();
                        Integer carrier = carrierEnum.getType();
                        if (redisClient.evalSetNx(CacheKey.THIRD_USR_LOCK + loginType.getType() + base + apkId + carrierEnum.getType() + i, expireTime)) {
                            String queueKey = getQueueKey(base, apkId, provinceId, carrier);
                            Long queueSize = redisClientTemp.getQueueSize(queueKey);
                            if (queueSize != null && queueSize > 0) {
                                continue;
                            }
                            ThirdUserQueryVo queryVo = new ThirdUserQueryVo();
                            long startTime = System.currentTimeMillis();
                            queryVo.setBase(base);
                            queryVo.setApkId(apkId);
                            queryVo.setCarrier(carrier);
                            queryVo.setProvinceId(i);
                            queryVo.setLength(maxSize);
                            queryVo.setBizId(config.getBizId());
                            if (redisClient.evalSetNx(queueKey + "QUEUE_LOCK", expireTime)) {
                                List<T> userList = selectUserList(queryVo);
                                if (userList != null && userList.size() > 0) {
                                    LOGGER.warn("apk {} base {} 省份{} 登录类型 {} 获取到的数据大小 {} 时间 {}", new Object[]{apkId, base, provinceId, loginType.getName(), userList.size(), System.currentTimeMillis() - startTime});
                                    for (T user : userList) {
                                        redisClientTemp.putToQueue(queueKey, user);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    private void updateLoginTask(int expireTime) {
        if (redisClient.evalSetNx(CacheKey.THIRD_USR_LOCK + loginType.getType(), expireTime)) {
            try {
                LOGGER.info("third login {}...", loginType.getType());
                Map<String, ApkPRIConfig> apkConfigMap = initApkOfProvince();
                String[] apks = apkConfigMap.keySet().toArray(new String[0]);
                apks = (String[]) RandomUtils.randomObjs(apks);
                Integer[] apkTaskNums = newTaskService.getLeftTaskNum(apks);
                List<Integer> loginNumList = apkLoginTypeService.getLeftLoginTypeNum(Arrays.asList(apks), loginType.getType());
                Integer[] queueSizes = taskLuaManager.getQueueSize(initTaskQueueKeys(apks, apkConfigMap));
                for (int i = 0; i < apks.length; i++) {
                    long start = System.currentTimeMillis();
                    String apk = apks[i];
                    String lockKey = CacheKey.THIRD_USR_LOCK + apk;
                    if (redisClient.evalSetNx(lockKey, expireTime)) {
                        ApkPRIConfig apkConfig = apkConfigMap.get(apk);
                        if (apkTaskNums[i] > 0 && loginNumList.size() > 0 && loginNumList.get(i) > 0) {
                            // 队列最大长度
                            int maxSize = simulatorManager.getApkCanUseSimulator(apk);
                            int needSize = maxSize - queueSizes[i];
                            if (needSize > loginNumList.get(i)) {
                                needSize = loginNumList.get(i);
                            }
                            if (needSize > 0) {
                                String bizId = apkConfig.getBizId();
                                if (StringUtils.isNotBlank(bizId)) {
                                    redisClient.put(bizId, apkConfig.getMark());
                                }
                                addApkTask(apkConfig, needSize);
                            }
                            LOGGER.warn("更新第三方登录 loginType {}  apk {}  loginKey {} maxSize {}  queueSizes {}  leftLogin {}  time {} ms", new Object[]{loginType, apk, loginIndexKey, maxSize,
                                    queueSizes[i], loginNumList.get(i), System.currentTimeMillis() - start});
                        } else {
                            LOGGER.warn("loginType {} apk {} loginKey {} queueSizes {} leftLogin {}", new Object[]{loginType, apk, loginIndexKey, queueSizes[i], loginNumList.get(i)});
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error("third login {}...", loginType.getType(), e);
            }
        }
    }



    private Map<Integer, String> getApkIdOfHsman() {
        List<ApkDevice> apkDevices = deviceConfigDAO.selectAllDevices();
        Map<Integer, String> map = new HashMap<>();

        for (ApkDevice apkDevice : apkDevices) {
            map.put(apkDevice.getApkId(), apkDevice.getHsman());
        }

        return map;
    }

    /**
     * initApkOfProvince:计算apk对应的省份信息
     *
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    private Map<String, ApkPRIConfig> initApkOfProvince() {
        // 1、省份下的apk信息
        ApkPRIConfig config = new ApkPRIConfig();
        config.setLoginType(loginType.getType());
        config.setIsDelete("0");
        List<ApkPRIConfig> configList = channelApkConfigDAO.selectApkListOfLogin(config);
        Map<Integer, Set<String>> apkMap = apkManager.getProvinceApkMap();

        Map<Integer, String> apkIdOfHsmanMap = getApkIdOfHsman();
        // 计算apk含有哪些省份
        Map<String, ApkPRIConfig> apkConfigMap = new HashMap<String, ApkPRIConfig>();

        for (ApkPRIConfig temp : configList) {
            Integer provinceId = temp.getProvinceId();
            String apk = temp.getMark();
            Set provinceSet = apkMap.get(provinceId);
            if (provinceSet != null && provinceSet.contains(apk)) {
                ApkPRIConfig apkConfig = apkConfigMap.get(apk);
                if (apkConfig == null) {
                    apkConfig = temp;
                    //设置指定机型
                    apkConfig.setAssignDevice(apkIdOfHsmanMap.get(temp.getId()));
                }
                Set<Integer> set = apkConfig.getProvinceIds();
                if (set == null) {
                    set = new HashSet<>();
                }
                set.add(provinceId);
                apkConfig.setProvinceIds(set);
                apkConfigMap.put(apk, apkConfig);
            }
        }
        return apkConfigMap;
    }


    private String getQueueKey(Integer baseId, Integer apkId, Integer provinceId, Integer carrier) {
        String qKey = null;
        if (loginType == LoginTypeEnum.SELF_CARD) {
            qKey = queueKey;
        } else {
            int apkIdOrBase = 0;
            if (baseId == null || baseId == ApkBaseEnum.OTHER.getType()) {
                apkIdOrBase = apkId;
            } else {
                apkIdOrBase = baseId;
            }
            qKey = queueKey + carrier + "_" + provinceId + "_" + apkIdOrBase;
        }
        return qKey;
    }


    protected String getIndexKey(Integer baseId, Integer apkId, Integer provinceId, Integer carrier) {
        String indexKey = null;
        if (loginType == LoginTypeEnum.SELF_CARD || loginType == LoginTypeEnum.WEIBO) {
            indexKey = loginIndexKey;
        } else {
            int apkIdOrBase = 0;
            if (baseId == null || baseId == ApkBaseEnum.OTHER.getType()) {
                apkIdOrBase = apkId;
            } else {
                apkIdOrBase = baseId;
            }
            indexKey = loginIndexKey + carrier + "_" + provinceId + "_" + apkIdOrBase;
        }
        return indexKey;
    }


    /**
     * addApkTask:添加任务
     *
     * @param apkConfig
     * @param needSize
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    private void addApkTask(ApkPRIConfig apkConfig, int needSize) {
        try {
            String apk = apkConfig.getMark();
            // apk的省份信息
            Set<Integer> provinceSet = apkConfig.getProvinceIds();
            if (provinceSet == null || provinceSet.size() == 0) {
                LOGGER.warn("第三方登录 apk {} base {} 登录类型 {} 没有获取到省份", new Object[]{apk, apkConfig.getBase(), loginType.getName()});
                return;
            }
            provinceSet.remove(-1);
            Integer[] provinces = provinceSet.toArray(new Integer[0]);
            provinces = ProvinceUtil.randomProvinces(provinces);
            LOGGER.warn("第三方登录 apk {} base {} 登录类型 {} 共{}个省", new Object[]{apk, apkConfig.getBase(), loginType.getName(), provinces.length});
            //如果是qq登录 同时生成一个qq授权登录任务

            ApkPRIConfig qqConfig = null;
            if (loginType == LoginTypeEnum.QQ_LOGIN) {
                //查询qq授权包配置
                ApkPRIConfig config = new ApkPRIConfig();
                config.setLoginType(LoginTypeEnum.QQ_ACCEPT_LOGIN.getType());
                config.setIsDelete("0");
                List<ApkPRIConfig> configList = channelApkConfigDAO.selectApkListOfLogin(config);
                if (configList != null && !configList.isEmpty()) {
                    qqConfig = configList.get(0);
                }
            }
            for (int i = 0; i < provinces.length; i++) {
                while (needSize > 0) {
                    Integer provinceId = provinces[i];
                    Integer apkId = apkConfig.getId();
                    Integer baseId = apkConfig.getBase();
                    Integer carrier = initQueryCarrier(apkConfig.getCarrier());
                    String qKey = getQueueKey(baseId, apkId, provinceId, carrier);
                    Object userObj = redisClientTemp.pollFromQueue(qKey);
                    if (userObj != null) {
                        LOGGER.warn("apk {} base {} 省份{} 登录类型 {} 获取到用户", new Object[]{apkId, baseId, provinceId, loginType.getName()});
                        ThirdUser user = (ThirdUser) userObj;
                        /**
                         * 猫用户 大于一分钟丢掉
                         */
                        if (loginType == LoginTypeEnum.SELF_MAO) {
                            if (System.currentTimeMillis() - user.getJoinTime() > SELF_MAO_USER_MAX_TIME) {
                                LOGGER.warn("apk {} base {} 省份{} 登录类型 {} 用户 {} 超时一分钟", new Object[]{apkId, baseId, provinceId, loginType.getName(), user.getImsi()});
                                continue;
                            }
                        }

                        String assignDevice = apkConfig.getAssignDevice();
                        String andriodVer = apkConfig.getAndriodVer();
                        if (StringUtils.isNotBlank(assignDevice)) {
                            String hsman = user.getHsman();
                            //机型不符合 过滤
                            if (StringUtils.isBlank(hsman) || !assignDevice.contains(hsman.toLowerCase())) {
                                continue;
                            }
                        }

                        if (StringUtils.isNotBlank(andriodVer)) {
                            String buildVersion = user.getBuildVersion();
                            //版本不符合过滤
                            if (StringUtils.isBlank(buildVersion) || Double.parseDouble(buildVersion) < Integer.parseInt(andriodVer)) {
                                continue;
                            }
                        }

                        user.setMark(apk);
                        user.setLoginType(loginType.getType());
                        user.setApkId(apkConfig.getId());
                        user.setBase(apkConfig.getBase());
                        user.setIsAssignDevice(apkConfig.getIsAssignDevice());
                        user.setCarrier(carrier);
                        user.setPayMax(apkConfig.getPayMax());
                        user.setPayMin(apkConfig.getPayMin());
                        user.setPayRate(apkConfig.getPayRate());
                        TaskStatusEnum status = newTaskService.addOfflineTask(user, apkConfig);
                        if (status == TaskStatusEnum.SUCCESS) {
                            if (loginType == LoginTypeEnum.QQ_LOGIN) {
                                user.setLoginType(LoginTypeEnum.QQ_ACCEPT_LOGIN.getType());
                                newTaskService.addOfflineTask(user, qqConfig);
                            }
                            needSize--;
                        } else if (status == TaskStatusEnum.HAS_DO) {
                            LOGGER.warn("第三方登录 apk {} 省份{} 登录类型 {} imsi {} status {} 在线用户已经做过", new Object[]{apk, provinceId, loginType.getName(), user.getImsi(), status.getType()});
                        } else if (status == TaskStatusEnum.NOT_DONE) {
                            LOGGER.warn("第三方登录 apk {} 省份{} 登录类型 {} imsi {} status {} 没做过", new Object[]{apk, provinceId, loginType.getName(), user.getImsi(), status.getType()});
                        } else if (status == TaskStatusEnum.HAVE_NO_SIMULATOR || status == TaskStatusEnum.EXEC_OVER || status == TaskStatusEnum.QUEUE_OUT_OF_RANGE
                                || status == TaskStatusEnum.LOGIN_OVER || status == TaskStatusEnum.LOGIN_PARAM_ERROR || status == TaskStatusEnum.APK_TASK_PARAM_ERROR) {
                            reuseUser(user, qKey);
                            break;
                        } else {
                            reuseUser(user, qKey);
                            needSize--;
                            LOGGER.warn("第三方登录 {} 省份 {} 登录类型 {} imsi {} status {} 添加任务失败", new Object[]{apk, provinceId, loginType.getName(), user.getImsi(), status.getType()});
                        }
                    } else {
                        LOGGER.warn("第三方登录 apk {} 省份 {} 登录类型 {} 运营商 {} 没有获取到用户", new Object[]{apk, provinceId, loginType.getName(), carrier});
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加 " + loginType.getName() + " 任务失败!", e);
        }
    }

    /**
     * 获取运营商类型
     *
     * @param carrierObj
     * @return
     */
    private int initQueryCarrier(String carrierObj) {
        if (StringUtils.isBlank(carrierObj)
                || loginType == LoginTypeEnum.MIGU
                || loginType == LoginTypeEnum.SELF_MOBILE_MIGU
                || loginType == LoginTypeEnum.THIRD_MIGU
                || loginType == LoginTypeEnum.THIRD_MIGU2
                || loginType == LoginTypeEnum.TEMP_MIGU
                || loginType == LoginTypeEnum.MIGU_VEDIO
                || loginType == LoginTypeEnum.MIGU_VEDIO2
                || loginType == LoginTypeEnum.MAO_MOBILE
                || loginType == LoginTypeEnum.SELF_CARD
                || loginType == LoginTypeEnum.BASIC
                ) {
            return CarrierEnum.MOBILE.getType();
        }

        if (loginType == LoginTypeEnum.SELF_TELECOM_MIGU) {
            return CarrierEnum.TELECOM.getType();
        }

        if (loginType == LoginTypeEnum.SELF_UNICOM_MIGU) {
            return CarrierEnum.UNICOM.getType();
        }
        String[] carriers = carrierObj.split(",");
        int index = (int) (Math.random() * carriers.length);
        return Integer.parseInt(carriers[index]);
    }


    private CarrierEnum[] initQueryCarrier() {
        if (loginType == LoginTypeEnum.MIGU
                || loginType == LoginTypeEnum.SELF_MOBILE_MIGU
                || loginType == LoginTypeEnum.THIRD_MIGU
                || loginType == LoginTypeEnum.THIRD_MIGU2
                || loginType == LoginTypeEnum.TEMP_MIGU
                || loginType == LoginTypeEnum.MIGU_VEDIO
                || loginType == LoginTypeEnum.MIGU_VEDIO2
                || loginType == LoginTypeEnum.MAO_MOBILE
                || loginType == LoginTypeEnum.SELF_CARD
                || loginType == LoginTypeEnum.BASIC
                ) {
            return new CarrierEnum[]{CarrierEnum.MOBILE};
        }

        if (loginType == LoginTypeEnum.SELF_TELECOM_MIGU) {
            return new CarrierEnum[]{CarrierEnum.TELECOM};
        }

        if (loginType == LoginTypeEnum.SELF_UNICOM_MIGU) {
            return new CarrierEnum[]{CarrierEnum.UNICOM};
        }

        if (loginType == LoginTypeEnum.WEIBO) {
            return new CarrierEnum[]{CarrierEnum.MOBILE};
        }

        if (loginType == LoginTypeEnum.OFFLINE || loginType == LoginTypeEnum.SELF_MAO || loginType == LoginTypeEnum.QQ_LOGIN || loginType == LoginTypeEnum.HISTORY_NEW_LOGIN) {
            return new CarrierEnum[]{CarrierEnum.TELECOM, CarrierEnum.UNICOM, CarrierEnum.MOBILE};
        }

        return new CarrierEnum[]{};
    }


    /**
     * reuseUser:用户重用
     *
     * @param user
     * @param queueKey
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    private void reuseUser(ThirdUser user, String queueKey) {
        if (loginType == LoginTypeEnum.SELF_CARD) {
            reuseSelfKashang(user);
        } else {
            redisClientTemp.putToQueue(queueKey, user);
        }
    }

    /**
     * reuseSelfKashang:自有卡用户状态更新
     *
     * @param user
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    private void reuseSelfKashang(ThirdUser user) {
        int i = 0;
        while (i <= 2) {
            try {
                SelfCardVo selfCardVo = (SelfCardVo) user;
                String bizId = selfCardVo.getBizId();
                String tokenId = selfCardVo.getTokenId();
                String imsi = selfCardVo.getImsi();
                String url = URL + "?bizId=" + bizId + "&tokenId=" + tokenId + "&imsi=" + imsi;
                String response = HttpUtil.getInfo(url, 1000);
                if (StringUtils.isNotBlank(response)) {
                    JSONObject responeObj = JSONObject.parseObject(response);
                    String status = responeObj.getString("resultCode");
                    if (StringUtils.isNotBlank(status) && status.equals("1")) {
                        break;
                    }
                }
            } catch (Exception e) {
                LOGGER.error("自有卡回调通知失败!", e);
            }
            i++;
        }
    }

    private String[] initTaskQueueKeys(String[] apks, Map<String, ApkPRIConfig> apkConfigMap) {
        if (apks != null && apks.length > 0) {
            String[] keys = new String[apks.length];
            for (int i = 0; i < apks.length; i++) {
                String apk = apks[i];
                keys[i] = CacheKey.VER_TASK_QUEUE + apkConfigMap.get(apk).getSysVer();
            }
            return keys;
        } else {
            return null;
        }
    }


    /**
     * @author xupengcheng 2018/4/10 10:46
     */
    List<MiguUser> selectMiguUserList(ThirdUserQueryVo queryVo) {

        // 咪咕登录省份限制
        List<MiguProvince> provinceList = miguProvinceConfigDao.selectMiguProvinceConfigList(null);
        if (provinceList == null || provinceList.isEmpty()) {
            return null;
        }
        for (MiguProvince province : provinceList) {
            // 如果配置了省份才可以做
            if (province.getProvinceId().intValue() == queryVo.getProvinceId().intValue()) {
                int postFix = queryVo.getApkId();
                Integer base = queryVo.getBase();
                if (base != null && base.intValue() != ApkBaseEnum.OTHER.getType()) {
                    postFix = base;
                }
                ClientEffectVo clientEffectVo = new ClientEffectVo();
                clientEffectVo.setDataSource(loginType.getType());
                clientEffectVo.setProvinceId(province.getProvinceId());
                clientEffectVo.setLength(queryVo.getLength());
                clientEffectVo.setPostfix(postFix);
                List<String> effectList = clientEffectDAO.selectEffectList(clientEffectVo);
                if (effectList != null && !effectList.isEmpty()) {
                    MiguUser queryUserVo = new MiguUser();
                    queryUserVo.setLength(queryVo.getLength());
                    queryUserVo.setTableName(queryVo.getTableName());
                    queryUserVo.setImsiList(effectList);
                    queryUserVo.setId(0);
                    List<MiguUser> userList = allMiguUserDAO.selectUserList(queryUserVo);
                    for (String imsi : effectList) {
                        ClientEffectVo effectVo = new ClientEffectVo();
                        effectVo.setImsi(imsi);
                        effectVo.setPostfix(postFix);
                        ClientRecordVo clientRecordVo = new ClientRecordVo();
                        clientRecordVo.setPostfix(postFix);
                        clientRecordVo.setCreateTime(new Date());
                        clientRecordVo.setImsi(imsi);
                        miguRecordUpdateBuffer.add(clientRecordVo);
                        miguEffectDelBuffer.add(effectVo);
                    }
                    return userList;
                }
            }
        }
        return null;
    }


    List<? extends ThirdUser> selectHistoryUserList(ThirdUserQueryVo queryVo) {
        Integer start = 0;
        String indexKey = getIndexKey(queryVo.getBase(), queryVo.getApkId(), queryVo.getProvinceId(), queryVo.getCarrier());
        Object indexObj = redisClient.get(indexKey);
        if (indexObj != null) {
            start = Integer.parseInt(indexObj.toString());
        }
        queryVo.setStart(start);
        QueryUserClientVo userVo = new QueryUserClientVo();
        userVo.setId((long) queryVo.getStart());
        userVo.setLength(queryVo.getLength());
        userVo.setProvince(queryVo.getProvinceId());
        userVo.setCarrier(queryVo.getCarrier());
        userVo.setTableName(queryVo.getTableName());
        List<UserClientInfo> clientList = userClientService.selectClientList(userVo);
        if (clientList != null && clientList.size() > 0) {
            List<ThirdUser> userList = new ArrayList<ThirdUser>();
            for (UserClientInfo clientInfo : clientList) {
                Long id = clientInfo.getId();
                if (id != null) {
                    if (start < clientInfo.getId().intValue()) {
                        start = clientInfo.getId().intValue();
                    }
                }
                clientInfo.setProvince(queryVo.getProvinceId());
                clientInfo.setTableName(queryVo.getTableName());
                if (clientManager.checkClient(clientInfo) != DataCheckStatusEnum.FAIL) {
                    ThirdUser thirdUser = new ThirdUser();
                    BeanCopierUtil.UserClient2ThirdUserBeanCopier.copy(clientInfo, thirdUser, null);
                    thirdUser.setId(clientInfo.getId().intValue());
                    thirdUser.setLoginType(queryVo.getLoginType().getType());
                    thirdUser.setProvince(queryVo.getProvinceId());
                    userList.add(thirdUser);
                }
            }
            redisClient.put(indexKey, start);
            return userList;
        } else {
            //跑完了重置
            redisClient.put(indexKey, 0);
            LOGGER.warn("apk {} base {} carrier {} 省份 {} 登录类型 {} 用户不够 当前下标 {}", new Object[]{queryVo.getApkId(), queryVo.getBase(), queryVo.getCarrier(), queryVo.getProvinceId(), loginType.getName(), start});
            return null;
        }

    }


    public String getLoginIndexKey() {
        return loginIndexKey;
    }

    public void setLoginIndexKey(String loginIndexKey) {
        this.loginIndexKey = loginIndexKey;
    }

    public LoginTypeEnum getLoginType() {
        return loginType;
    }

    public void setLoginType(LoginTypeEnum loginType) {
        this.loginType = loginType;
    }

    public String getQueueKey() {
        return queueKey;
    }

    public void setQueueKey(String queueKey) {
        this.queueKey = queueKey;
    }


}
